package com.example.extenddemo.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import com.example.extenddemo.utils.MinIOConst;
import com.sleep.miniosleep.util.MinIOUtil;
import io.minio.MinioClient;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @ClassName TestMinIOController
 * @Description TODO
 * @Author 郭敖
 * @Date 2024年03月28日 16:25
 * @Version 1.0
 */
@RestController
@RequestMapping("/file")
@RequiredArgsConstructor
public class TestMinIOController{
    private final MinIOUtil minIOUtil;

    @PostMapping("/uploadImage")
    public String testUpload(MultipartFile file){
        minIOUtil.uploadFile("mydemo",file,"testDemo1",file.getContentType());
        return "success";
    }

    @PostMapping("/copyFile")
    public String copyFile(HttpServletResponse response) throws FileNotFoundException {
        InputStream file = minIOUtil.getObject(MinIOConst.BUCKET_NAME, "testDemo1");
        FileOutputStream outputStream = new FileOutputStream("D:\\testDemo1.jpg");
        try{
            IoUtil.copy(file,response.getOutputStream());
            file = minIOUtil.getObject(MinIOConst.BUCKET_NAME, "testDemo1");
            IoUtil.copy(file,outputStream);
            //response.getOutputStream().flush();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                file.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
                if(outputStream != null){
                    outputStream.close();

                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return "success";
    }
}
